import { View, Image, Text, CoverImage, RichText } from '@tarojs/components'
import { useState, useEffect, useCallback, useRef } from 'react'
import LgButton from '../../components/button'
import Header from '../../components/navCustomBar'
import Taro from '@tarojs/taro'
import { HttpGet, HttpPut, HttpPost, HttpDelete } from '../../../network/servers'
import Utils from '../../../utils/index'
import { connect } from 'react-redux'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '../../components/utils';
import { CalendarPicker, List, Popup, VirtualInput, Input, Dialog } from 'antd-mobile'
import { LgPopLayer } from "lancoo-ui-mobile";
import '../../images/public/style.css'
import './index.scss'


const storage = getStorage()
var wx = require('weixin-js-sdk')
const {
  getNowToken,
  getQueryVariable,
} = Utils


function App(props) {

  let {
    userInfo,
    baseUrl,
  } = props

  const getToken = () => {
    if (getQueryVariable('env') == 'weapp') {
      return getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || getQueryVariable('lg_tk')
    }
  }

  const inputRef = useRef(null);

  const [detail, setDetail] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [imgList, setImgList] = useState([]);

  const [newsId, setNewsId] = useState("");

  const [isRead, setIsRead] = useState(0);
  const [height, setHeight] = useState(0);

  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [cover, setCover] = useState('')

  const [typeId, setTypeId] = useState('')
  const [typeName, setTypeName] = useState('')


  const getCommonData = () => {
    if (Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram') {
      // 小程序端的h5
      if (!baseUrl) {
        // 直接跳转当前页面

      } else {
        console.log('小程序');

        //应用内跳转
        let instance = Taro.getCurrentInstance()
        if (instance.router?.params) {
          let params = instance.router.params
          let id = params.id
          if (!id) return;
          // console.log(params);
          setIsRead(isRead)
          setNewsId(id)

          let url = "/api/news/info//edit/detailed"
          HttpGet({
            url,
            data: {
              newsId: id,
            }
          }).then(res => {
            if (res.code == 200 && res.data) {
              let data = res.data
              console.log(data.newsCoverPath, 'data.newsCoverPath');

              setTitle(data.newsTitle)
              // setContent((data.newsContent).replace(/<[^>]*>|<\/[^>]*>/gm, ""))
              setContent(data.newsContent)
              setCover(JSON.parse(JSON.stringify(data.newsCoverPath)))
              setTypeId(data.newsTypeId)
              setTypeName(data.newsTypeName)
              let attachments = res.data.newsAttachmentVoList
              if (attachments && attachments.length !== 0) {
                let imgArr = [], fileArr = [];
                attachments.map(item => {
                  let fileType = Utils.getFileType(item?.attachmentName)
                  if (fileType == 'img') {
                    item.url = item.attachmentUrl
                    item.size = item.attachmentSize
                    item.fileName = item.attachmentName
                    imgArr.push(item)
                  } else {
                    item.url = item.attachmentUrl
                    item.size = item.attachmentSize
                    item.fileName = item.attachmentName
                    fileArr.push(item)
                  }
                })

                setFileList(fileArr)
                setImgList(imgArr)
              }
              setIsRead(res.data.readStatus)
              setDetail(res.data)
            } else {
              Taro.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      }
    } else {
      // app内 1.应用内跳转(不需要获取通知地址和用户信息) 2.直接跳转
      let instance = Taro.getCurrentInstance()

      const browserController = getBrowserController()
      let height = browserController.getStatusBarHeight()
      setHeight(height)
      if (instance.router?.params) {
        let params = instance.router.params
        let id = params.id
        if (!id) return;
        // console.log(params);

        setIsRead(isRead)
        setNewsId(id)

        HttpGet({
          // url: '/api/commons/school/user/self',
          url: `api/common/user`,
          data: {
            token: getNowToken()
          },

        }).then((res1) => {
          HttpGet({
            // url: 'api/commons/system/server/info',
            url: 'api/common/system/list',
            data: {
              sysIds: '260',
            },
          }).then((response) => {
            let url = response.data.webSvrAddr + "/api/news/info//edit/detailed"
            HttpGet({
              url,
              data: {
                newsId: id,
              }
            }).then(res => {
              if (res.code == 200 && res.data) {
                let data = res.data
                console.log(data.newsCoverPath, 'data.newsCoverPath');

                setTitle(data.newsTitle)
                // setContent((data.newsContent).replace(/<[^>]*>|<\/[^>]*>/gm, ""))
                setContent(data.newsContent)
                setCover(JSON.parse(JSON.stringify(data.newsCoverPath)))
                setTypeId(data.newsTypeId)
                setTypeName(data.newsTypeName)
                let attachments = res.data.newsAttachmentVoList
                if (attachments && attachments.length !== 0) {
                  let imgArr = [], fileArr = [];
                  attachments.map(item => {
                    let fileType = Utils.getFileType(item?.attachmentName)
                    if (fileType == 'img') {
                      item.url = item.attachmentUrl
                      item.size = item.attachmentSize
                      item.fileName = item.attachmentName
                      imgArr.push(item)
                    } else {
                      item.url = item.attachmentUrl
                      item.size = item.attachmentSize
                      item.fileName = item.attachmentName
                      fileArr.push(item)
                    }
                  })

                  setFileList(fileArr)
                  setImgList(imgArr)
                }
                setIsRead(res.data.readStatus)
                setDetail(res.data)
              } else {
                Taro.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          })
        })
      }
    }
  }

  const [typeList, setTypeList] = useState([])
  //获取全部类型
  const getTypeList = () => {
    let url = 'api/weekly/general/partition/list'
    HttpGet({
      url,
      data: {
        schoolId: storage.get('schoolId') || Utils.getQueryVariable('schoolId') || userInfo.schoolId,
        schoolLevel: storage.get('schoolLevel') || userInfo.schoolLevel
      }
    }).then((res) => {
      if (res.code == 200) {
        let data = res.data;
        setTypeList(data)
      }
    })
  }

  const goBack = () => {
    Taro.redirectTo({
      url: '/pages/newsInfoApp/index'
    })
  }

  const initWxSdk = async () => {
    const params = getWxSDKParams(['previewImage', 'getLocation'])
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log('ready')
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log(res)
    });
  }

  useEffect(() => {
    document.title = '分区设置'
    if (window.__wxjs_environment == 'miniprogram') {
      initWxSdk()
    }
    getCommonData()
    getTypeList()
    return () => {
      if (Utils.getSystemInfo() == 'weapp') {
        document.title = '分区设置'
        window.getNoticeList && typeof window.getNoticeList == 'function' && window.getNoticeList()
      }
    }
  }, []);

  const okEdit = () => {
    console.log(temp_saveWeeklyPlanBoList)
    let tempdata = [...gap_day]
    let flag = false
    temp_saveWeeklyPlanBoList.forEach((i, index) => {
      if (i.departmentName == '' || i.planContent == '') {
        flag = true
      }
    })
    if (flag) {
      Taro.showToast({
        title: '请选择部门名称和填写事务安排',
        icon: 'none',
        duration: 2000
      })
      return
    } else {
      temp_saveWeeklyPlanBoList.forEach((i, index) => {
        tempdata[nowBeSelectPlan.index].saveWeeklyPlanBoList[index] = i
      })
      setGap_day(tempdata)
      setPopupVisible(false)
    }
  }

  const addArrange = () => {
    let temp = [...temp_saveWeeklyPlanBoList]
    temp.push({
      departmentName: '',
      planContent: ''
    })
    setTemp_saveWeeklyPlanBoList(temp)
  }

  const deleteRow = (index) => {
    console.log(index)
    if (temp_saveWeeklyPlanBoList.length == 1) {
      Taro.showToast({
        title: '至少保留一行！',
        icon: 'none',
        duration: 2000
      })
      return
    }
    console.log(temp_saveWeeklyPlanBoList)
    let tempData = [...temp_saveWeeklyPlanBoList]
    tempData.splice(index, 1)
    setTemp_saveWeeklyPlanBoList(tempData)
  }

  const [editVisiable, setEditVisiable] = useState(false)
  const [addVisiable, setAddVisiable] = useState(false)
  const [nowEditItem, setNowEditItem] = useState({})
  const editVisiableFunc = (i) => {
    console.log(i)
    setEditVisiable(true)
    setNowEditItem(i)
  }
  const changeEditContent = (val) => {
    console.log(val)
    let obj = { ...nowEditItem }
    obj.partitionName = val
    setNowEditItem(obj)
  }

  const ok_btn = (type) => {
    let url = 'api/weekly/general/partition/save'
    console.log(userInfo)
    if (type == 'edit') {
      if (nowEditItem.partitionName == '') {
        Taro.showToast({
          title: '请先填写分区名称！',
          icon: 'none',
          duration: 2000
        })
        return
      }
      HttpPost({
        url,
        data: {
          partitionId: nowEditItem.partitionId ? nowEditItem.partitionId : '',
          partitionName: nowEditItem.partitionName,
          schoolId: storage.get('schoolId') || userInfo.schoolId,
          schoolLevel: userInfo.schoolLevel
        }
      }).then((data) => {
        if (data.code == 200) {
          getTypeList()
          setNowEditItem({})
          setEditVisiable(false)
          setTimeout(() => {
            Taro.showToast({
              title: '修改成功~',
              duration: 2000
            })
          }, 500);
        }
      })
    } else {
      if (addContent == '') {
        Taro.showToast({
          title: '请先填写分区名称！',
          icon: 'none',
          duration: 2000
        })
        return
      }
      HttpPost({
        url,
        data: {
          partitionName: addContent,
          schoolId: storage.get('schoolId') || userInfo.schoolId,
          schoolLevel: storage.get('schoolLevel') || userInfo.schoolLevel
        }
      }).then((data) => {
        if (data.code == 200) {
          getTypeList()
          setAddVisiable(false)
          setTimeout(() => {
            Taro.showToast({
              title: '添加成功~',
              duration: 2000
            })
          }, 500);
        }
      })
    }

  }

  const deleteBtn = (i) => {
    HttpDelete({
      url: '/api/weekly/general/partition/del?partitionId=' + i.partitionId,
    }).then((result) => {
      if (result.code === '200') {
        getTypeList();
        Taro.showToast({
          title: '删除成功',
          duration: 2000,
          mask: true
        })
      }
    })
  }

  const [addContent, setAddContent] = useState('')
  const changeAddContent = (val) => {
    console.log(val)
    setAddContent(val)
  }

  const addFQ = useCallback(() => {
    Dialog.alert({
      content: <div className='edit_area'>
        <div className='edit_title'>添加分区</div>
        <div className='line'></div>
        <Input ref={inputRef} onChange={(val) => { changeAddContent(val) }} style={{ backgroundColor: '#f7f7f7', width: '85vw', margin: '20px auto', height: '44px', padding: '0 12px' }} placeholder='请输入分区名称' clearable />
        <div onClick={() => { ok_btn('add') }} className='ok_btn'>确定</div>
      </div>,
      onConfirm: () => {
        console.log('Confirmed')
      },
    })
  }, [addVisiable])

  useEffect(() => {
    if (addVisiable && inputRef.current) {
      inputRef.current?.focus();
      console.log(inputRef.current)
    }
  }, [addVisiable, inputRef.current]);

  return (
    <View className="partitionSetting">
      {
        Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram' ?
          "" :
          <Header
            goMainPage={() => { console.log(321312) }}
            className='header-top'
            mainTitle='分区设置'
            mainTitleBlod={false}
            isTitlePositionLeft={true}
            needMainIcon={process.env.TARO_ENV == 'weapp' ? false : true}
          />
      }
      <View className='setting_list'>
        {
          typeList.length > 0 ? <>
            {
              typeList.map(i => {
                return (
                  <div className='setting_item'>
                    <div>{i.partitionName}</div>
                    <div className='setting_btn'>
                      <div className='setting_edit' onClick={() => { editVisiableFunc(i) }}></div>
                      <div onClick={() => { deleteBtn(i) }} className='setting_delete'></div>
                    </div>
                  </div>
                )
              })
            }
          </> : <div className='empty'>暂无分区数据，请添加</div>
        }
      </View>
      <View className="index_footer">
        <LgButton className="send_btn" type='B' height={88} onClick={() => {
          // addFQ()
          setAddVisiable(true)
        }} >添加分区</LgButton>
      </View>
      <Popup
        visible={editVisiable}
        showCloseButton
        onMaskClick={() => {
          setEditVisiable(false)
        }}
        onClose={() => {
          setEditVisiable(false)
        }}
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          minHeight: '25vh',
          position: 'fixed',
        }}
      >
        <div className='edit_area'>
          <div className='edit_title'>更改分区名称</div>
          <div className='line'></div>
          <Input onChange={(val) => { changeEditContent(val) }} key={nowEditItem.partitionId} defaultValue={nowEditItem.partitionName} style={{ backgroundColor: '#f7f7f7', width: '85vw', margin: '20px auto', height: '44px', padding: '0 12px' }} placeholder='请输入内容' clearable />
          <div onClick={() => { ok_btn('edit') }} className='ok_btn'>确定</div>
        </div>
      </Popup>
      {
        addVisiable ? 
        <Popup
        visible={addVisiable}
        showCloseButton
        onMaskClick={() => {
          setAddVisiable(false)
        }}
        onClose={() => {
          setAddVisiable(false)
        }}
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          height: '25vh',
          position: 'fixed',
          zIndex: '1000'
        }}
      >
        <div className='edit_area'>
          <div className='edit_title'>添加分区</div>
          <div className='line'></div>
          <Input ref={inputRef} onChange={(val) => {changeAddContent(val)}} style={{backgroundColor: '#f7f7f7', width: '85vw', margin: '20px auto', height: '44px', padding: '0 12px'}} placeholder='请输入分区名称' clearable />
          <div onClick={() => {ok_btn('add')}} className='ok_btn'>确定</div>
        </div>
      </Popup> : ''
      }

    </View>
  )
}

const mainProps = ({ commonData }) => {

  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl,
    systemInfo1: commonData.systemInfo,
  }
}

export default connect(mainProps)(App);
